package com.ysz.timewheel.server.task;

import com.ysz.timewheel.TimeWheel;
import com.ysz.timewheel.server.struct.Node;
import com.ysz.timewheel.server.struct.TimeWheelStruct;

import java.util.Objects;

/**
 * @ClassName PollingTask
 * @Description TODO
 * @Data 10:30
 * @Version 1.0
 * @Author ysz
 */
public class PollingTask implements Runnable {
    @Override
    public void run() {
        //获取头节点
        Node currNode = TimeWheelStruct.getFirst();
        while (true) {
            try {
                //有扫描次数
                if (Objects.nonNull(currNode.getNumberOfScans()) && currNode.getNumberOfScans() > 0) {
                    if (Objects.nonNull(currNode.getCurrentIndex())) {
                        //从超时map移除
                        TimeWheel.getTimeOutTimeClients().remove(currNode.getCurrentIndex());
                        currNode.setNumberOfScans(0);
                    }
                } else {
                    //更新扫描次数
                    currNode.setNumberOfScans(currNode.getNumberOfScans() == null ? 0 : currNode.getNumberOfScans() + 1);
                }
                //不断移动指针指向下一个
                currNode = currNode.getNext();
                Thread.sleep(1000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
